package cn.yangliu.kindeditor.config;

import cn.yangliu.kindeditor.web.FileManagerServlet;
import cn.yangliu.kindeditor.web.ShowServlet;
import cn.yangliu.kindeditor.web.UploadServlet;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * 作者 杨柳
 * 时间 2017-09-24 17:15
 * 描述
 */
@Configuration
@EnableConfigurationProperties(value = KindeditorProperties.class)
//@ConditionalOnClass(HelloService.class)
@ConditionalOnProperty(prefix = "spring.kind-editor", value = "enable", matchIfMissing = true)
public class KindeditorAutoConfiguration {

    @Resource
    private KindeditorProperties properties;

    @Bean
    public ServletRegistrationBean kindeditorUploadServlet() {
        ServletRegistrationBean bean = new ServletRegistrationBean();
        bean.setServlet(new UploadServlet());
        bean.addUrlMappings(properties.getUploadUrl());
        return bean;
    }

    @Bean
    public ServletRegistrationBean kindeditorFileManagerServlet() {
        ServletRegistrationBean bean = new ServletRegistrationBean();
        bean.setServlet(new FileManagerServlet());
        bean.addUrlMappings(properties.getFileUrl());
        return bean;
    }

    @Bean
    public ServletRegistrationBean kindeditorShowServlet() {
        ServletRegistrationBean bean = new ServletRegistrationBean();
        bean.setServlet(new ShowServlet());
        String url = properties.getGlobalUrlPreffix();
        if (url.startsWith("http://") || url.startsWith("https://")) {
            url = "/kindeditor";
        }
        url += "/*";
        bean.addUrlMappings(url);
        return bean;
    }

}
